<?php
class App_Page_Model_Block extends Main_Db_Table_Abstract
{
	/**
	 * @var string
	 */
	protected $_name = 'page_block';
	
	/**
	 * @var string
	 */
	protected $_primary = 'id';
	
	/**
	 * @var array
	 */
	protected $_fields = array(
		'id',
	    'name',
		'page_id',
	  	'f_active',
		'lang_id',
		'plugin_id',
		'content',
		'description'
	);
	
	/**
	 * @return void
	 */
	public function init() 
	{
	}

	/**
	 * @param array $data
	 * @return bool
	 */
	public function insertItem($data) 
	{
		$dataOk = $this->beforeSave($data, array(
			'name', 'page_id', 'f_active',
			'content', 'description'  
		), array(
			'name', 'content', 'description'
		));
		
		$dataOk['lang_id'] = $data['lang_id'];
		$dataOk['plugin_id'] = $data['plugin_id'];
		
		//var_dump($dataOk); exit;
		
		$result = $this->insert($dataOk);
		
		return $result;
	}
	
	/**
	 * @param array $data
	 * @param int $id
	 * @return bool
	 */
	public function updateItem($data, $id)
	{
		$id = $this->escape($id);
		$dataOk = $this->beforeSave($data, array(
			'name', 'page_id', 'f_active', 'lang_id', 'plugin_id',
			'content', 'description'  
		), array(
			'name', 'content', 'description'
		));
    	
    	return $this->update($dataOk, "id={$id}");
	}
	
	/**
	 * @param int $id
	 * @return array
	 */
	public function getItemById($id) 
	{
		$id = $this->escape($id);
		
		$sql = "
			SELECT 
				p_b.id
				, p_b.name
				, p_b.f_active
				, p_b.lang_id
				, p_b.page_id
				, p_b.plugin_id
				, p_b.content
				, p_b.description
			FROM
				page_block p_b
			WHERE
				p_b.id={$id}		
		";
				
		$list = $this->getAdapter()->fetchRow($sql);

		return $list;
	}
	
	/**
	 * @param string $name
	 * @param int $pageId
	 * @param int $langId 
	 * @return array
	 */
	public function getItemByNameAndPageId($name, $pageId, $langId)
	{
		$name = $this->escape($name);
		
		if ($pageId != null) {
			$pageId = $this->escape($pageId);
			$pageIdCondition = "p_b.page_id = {$pageId}";
		} else {
			$pageIdCondition = "p_b.page_id IS NULL";
		}
		
		$sql = "
			SELECT 
				p_b.id
				, p_b.name
				, p_b.f_active
				, p_b.lang_id
				, p_b.page_id
				, p_b.plugin_id
				, p_b.content
				, p_b.description
			FROM
				page_block p_b
			WHERE
				p_b.name='{$name}' AND {$pageIdCondition} 			
		";

		$list = $this->getAdapter()->fetchRow($sql);
		return $list;
	}
	
	
	/**
	 * @param int $id
	 * @return bool
	 */
	public function deleteItem($id) 
	{
		$id = $this->escape($id);
		return $this->delete("id={$id}");
	}
	
} 
